package com.pointcircle.core.web.annotation;

import java.lang.reflect.Method;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ApiPermissionAspect {
	
	@Before(value = "@target(com.pointcircle.core.web.annotation.ApiPermissionConfig) && "
			+ "@annotation(com.pointcircle.core.web.annotation.ApiPermissionConfig)")
	public void checkPermission(JoinPoint jp) {
		Object target = jp.getTarget();
		ApiPermissionConfig baseApiPermissionConfig = 
			AnnotationUtils.findAnnotation(target.getClass(), ApiPermissionConfig.class);
		MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        Method method = methodSignature.getMethod();
		ApiPermissionConfig apiPermissionConfig = AnnotationUtils.getAnnotation(method, ApiPermissionConfig.class);
		String permission = "api:" + (baseApiPermissionConfig == null ? "" : baseApiPermissionConfig.value() + ":") 
			+ apiPermissionConfig.value();
		Subject subject = SecurityUtils.getSubject();
		subject.checkPermission(permission);
	}
}
